<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size:18px ">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item>品牌</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider style="margin-bottom: 50px"></el-divider>

    <el-table
        :data="tableData"
        style="width: 100%" highlight-current-row>
      <!--至少又一列时不设置宽度的，因为不设置宽度会占据到整行的所有数据-->
      <!--      <el-table-column type="index"></el-table-column>-->
      <el-table-column prop="id" label="ID" width="80" header-align="center" align="center"></el-table-column>
      <el-table-column prop="name" label="品牌名称" width="150" header-align="center" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="logo" label="LOGO" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="pinyin" label="拼音" header-align="center" align="center" width="150"></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" width="150"></el-table-column>
      <el-table-column prop="keywords" label="关键词列表" header-align="center" width="150"></el-table-column>
      <el-table-column prop="sort" label="排序序号" header-align="center" align="center" width="150"></el-table-column>
      <el-table-column label="是否启用" header-align="center" align="center" width="150">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="changeStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column width="100" label="操作" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     @click="showEditFormDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--以下是修改品牌信息DiaLog（嵌套表单的对话框）-->
    <el-dialog title="修改信息" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="editForm.pinyin"></el-input>
        </el-form-item>
        <el-form-item label="LOGO" prop="logo">
          <el-input v-model="editForm.logo"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="editForm.keywords"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <template slot-scope="scop">
            <el-switch
                v-model="editForm.enable"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ccc">
            </el-switch>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "brandListView",
  data() {
    return {
      tableData: [],
      dialogFormVisible: false, /*此属性用来控制dialog的显示状态，默认关闭*/
      editForm: {
        name: '',
        pinyin: '',
        logo: '',
        description: '',
        keywords: '',
        sort: '',
        enable: ''
      },
      formLabelWidth: '120px',
      rules: {
        /*trigger表示检查什么情况会触发，blur表示当控件丢失焦点时触发检查*/
        name: [
          {required: true, message: '请输入品牌名称', trigger: 'blur'},
          {min: 2, max: 15, message: '品牌名须在 2 到 15 个字符', trigger: 'blur'}
        ],
        pinyin: [
          {required: true, message: '请输入品牌拼音', trigger: 'blur'},
          {min: 5, max: 100, message: '请确保拼音输入正确', trigger: 'blur'}
        ],
        logo: [
          {required: true, message: '请输入品牌logo的url', trigger: 'blur'},
          {max: 255, message: 'url地址请少于255个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入品牌简介', trigger: 'blur'},
          {min: 2, max: 255, message: '请输入大于五个字符的品牌描述', trigger: 'blur'}
        ],
        keywords: [
          {required: true, message: '请输入品牌的关键字描述(使用,分割)', trigger: 'blur'},
          {min: 0, max: 125, message: '关键字必须在125个字符以内', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入品牌排序序号', trigger: 'blur'},
          {pattern: /^([0-9]{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号须在0到99之间', trigger: 'blur'}
        ]
      }
    }
  }, methods: {
    //在列表中设置启用状态
    changeStatus(brand) {
      let url = "http://localhost:15722/brands/" + brand.id;
      console.log(brand.enable);
      //开关从开启->关闭 传递过来的就是0 关闭->开启 传递过来的就是1
      if (brand.enable == 0) {
        url += "/disable";
      } else {
        url +=  "/enable";
      }
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        let text = ["禁用", "启用"];
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            message: text[brand.enable] + '【' + brand.name + '】品牌状态成功!'
          });
          this.loadBrandList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
              this.dialogFormVisible = false;
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
              this.dialogFormVisible = false;
            }
          });
        }
      });
    },
    //显示修改需要弹出的Dialog
    showEditFormDialog(brand) {
      // this.dialogFormVisible=true;
      // this.editForm = brand;
      // console.log("这是编辑按钮的：" + brand.id);

      //通过发送请求判断数据是否存在
      let url = "http://localhost:15722/brands/" + brand.id;
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '数据查询失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '数据查询失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }
      });
    },
    //在修改弹窗中，点击确认触发此方法
    submitEditForm() {
      let url = "http://localhost:15722/brands/" + this.editForm.id + "/update";
      let forData = this.qs.stringify(this.editForm);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, forData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            message: '修改【' + this.editForm.name + '】品牌成功!'
          });
          this.loadBrandList();
          this.dialogFormVisible = false;
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
              this.dialogFormVisible = false;
            }
          });
        } else {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
              this.dialogFormVisible = false;
            }
          });
        }
      });
    },
    //打开删除提示
    openDeleteConfirm(brand) {
      let message = '此操作将永久删除【' + brand.name + '】品牌，是否继续?'
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        /*成功后触发此方法*/
        this.handleDelete(brand);
      }).catch(() => {
        /*取消之后进行的处理*/
      });
      console.log("这是删除按钮的：" + brand.id);
    },
    //处理删除
    handleDelete(brand) {
      let url = "http://localhost:15722/brands/" + brand.id + "/delete";
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            message: '删除【' + brand.name + '】品牌成功!'
          });
          //刷新列表
          this.loadBrandList();
        } else {
          this.$alert('删除数据不存在！', '删除失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }
      });
    },
    /*获取用户列表的方法*/
    loadBrandList() {
      let url = "http://localhost:15722/brands";
      console.log(url)
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data;
        }
      });
    }
  },
  mounted() {
    /*mounted中永远不写实质的执行代码
    * mouted中永远都是调用方法
    * 就算只有一条代码也要封装为一个函数
    * */
    /*对品牌列表进行初始化*/
    this.loadBrandList();
  }
}
</script>

<style scoped>

</style>